package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelLogger"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"go-fox-edge-channel-serial/channelEntity"
	"time"
)

type executeService struct {
}

func (e *executeService) execute(serialChannelEntity *channelEntity.SerialChannelEntity, requestVO *commRedisRpc.ChannelRequestVO) (*commRedisRpc.ChannelRespondVO, error) {
	if requestVO.Send == nil || requestVO.Send == "" {
		return nil, errors.New("发送数据不能为空！")
	}
	if requestVO.Timeout == 0 {
		return nil, errors.New("超时参数不能为空！")
	}
	if requestVO.Timeout > 10*1000 {
		return nil, errors.New("超时参数不能大于10秒！")
	}
	if serialChannelEntity.Config.FullDuplex {
		return nil, errors.New("必须工作在半双工模式下")
	}

	// 检查串口
	if !serialChannelEntity.SerialPort.IsOpen() {
		return nil, errors.New("串口不存在或者未打开！")
	}

	// 格式转换
	send := Hex.DecodeString(requestVO.Send)

	// 打印发送日志
	channelLogger.PrintChannelDebugLogger(requestVO.Name, "发送", requestVO.Send)

	// 发送数据
	cnt, err := serialChannelEntity.SerialPort.Write(send)
	if err != nil {
		return nil, err
	}
	if cnt == 0 {
		return nil, errors.New("发送失败")
	}

	buffer := make([]byte, 16*1024)
	cnt, err = serialChannelEntity.SerialPort.Read(buffer, int64(requestVO.Timeout))
	if err != nil {
		return nil, err
	}
	if cnt == 0 {
		return nil, errors.New("接收失败")
	}

	// 打印接收日志
	recv := Hex.EncodeToString(buffer[0:cnt])
	channelLogger.PrintChannelDebugLogger(requestVO.Name, "接收", recv)

	// 通知第三方服务：接收到数据
	channelStatus.Param.UpdateParamStatus(requestVO.Name, "recvTime", time.Now().UnixMilli())

	respondVO := commRedisRpc.Type.ChannelRespondVO.Ok(requestVO)
	respondVO.Recv = recv
	return respondVO, nil
}
